package shujia.day12.homework;

import java.util.*;

/*
    实现List和Map数据的转换。具体要求如下：
    功能1：定义方法public void listToMap( ){ }将List中Student元素封装到Map中
        1)    使用构造方法Student(int id,String name,int age,String sex )创建多个学生 信息并加入List
        2)    遍历List ，输出每个Student信息
        3)    将List中数据放入Map ，使用Student的id属性作为key ，使用Student对象 信息作为value
        4)    遍历Map ，输出每个Entry的key和value
    功能2：定义方法public void mapToList( ){ }将Map中Student映射信息封装到List
        1)    创建实体类StudentEntry ，可以存储Map中每个Entry的信息
        2)    使用构造方法Student(int id,String name,int age,String sex )创建多个学生 信息，并使用Student的id属性作为key ，存入Map
        3)    创建List对象，每个元素类型是StudentEntry
        4)    将Map中每个Entry信息放入List对象
 */
public class Test2 {
    public static void main(String[] args) {
        ArrayList<Student> list1 = new ArrayList<>();

        list1.add(new Student(1001, "张三1", 18, "男"));
        list1.add(new Student(1002, "张三2", 18, "男"));
        list1.add(new Student(1003, "张三3", 15, "女"));
        list1.add(new Student(1005, "张三5", 16, "男"));
        list1.add(new Student(1006, "张三6", 17, "女"));
        HashMap<Integer, Student> studentMap = listToMap(list1);
        System.out.println("=======================================");

        List<StudentEntry> entryList = mapToList(studentMap);
        for (StudentEntry studentEntry : entryList) {
            Map.Entry<Integer, Student> entry = studentEntry.getEntry();
            Integer id = entry.getKey();
            Student stu = entry.getValue();
            System.out.println(id + "： " + stu);
        }


    }

    public static List<StudentEntry> mapToList(HashMap<Integer, Student> map) {
        ArrayList<StudentEntry> list1 = new ArrayList<>();
        Set<Map.Entry<Integer, Student>> entries = map.entrySet();
        for (Map.Entry<Integer, Student> entry : entries) {
            StudentEntry studentEntry = new StudentEntry(entry);
            list1.add(studentEntry);
        }
        return list1;

    }


    public static HashMap<Integer, Student> listToMap(List<Student> list) {
        HashMap<Integer, Student> map1 = new HashMap<>();

        for (Student student : list) {
            System.out.println(student);
            int id = student.getId();
            map1.put(id, student);
        }

        System.out.println("--------------");
        Set<Map.Entry<Integer, Student>> entries = map1.entrySet();
        for (Map.Entry<Integer, Student> entry : entries) {
            Integer id = entry.getKey();
            Student stu = entry.getValue();
            System.out.println(id + "-" + stu);
        }


        return map1;
    }
}
